<?php

namespace app\index\controller;

use think\Controller;
use app\index\model\Users as UserModel;
use app\index\model\Shoper as ShoperModel;
use app\index\model\Admin as AdminModel;
use think\Cookie;
use think\Request;
use think\Session;
use sina\SaeTOAuthV2;
use sina\SaeTClientV2;



class User extends Controller
{
	public function register()
	{
		return $this->fetch();
	}

	//查询数据库验证邮箱是否可用-----------------------------------------------
	public function emailCheck()
	{
		$email = $_POST['email'];
		$user = UserModel::get(['email' => $email]);
		$shoper = ShoperModel::get(['shop_email' => $email]);
		$admin = AdminModel::get(['admin_email' => $email]);
		if ($user || $admin || $shoper) {
			echo json_encode(['state' => 1]);
		} else {
			echo json_encode(['state' => 0]);
		}
	}

	//查询数据库店铺名是否存在
	public function shopNameCheck()
	{
		$username = $_POST['username'];
		$user = UserModel::get(['username' => $username]);
		$shoper = ShoperModel::get(['shop_name' => $username]);
		$admin = AdminModel::get(['admin_name' => $username]);
		if ($user || $admin || $shoper) {
			echo json_encode(['state' => 5]);
		} else {
			echo json_encode(['state' => 6]);
		}
	}

	//邮箱用户注册信息插入数据库
	public function dataInsert()
	{
		$userType = $_POST['userType'];
		$ip = $_SERVER['REMOTE_ADDR'];
		$ip == '::1' ? $ip = ip2long('127.0.0.1') : $ip = ip2long($ip);
		$data['create_ip'] = $ip;
		$data['create_time'] = date('Y-m-d H:i:s');
		if ($userType == 1) {
			$data['email'] = $_POST['email'];
			$data['password'] = md5($_POST['password']);
			$data['grade'] = 10;
			$data['username'] = 1;
			$data['phone'] = 1;

			$result = UserModel::create($data);
			if ($result) {
				echo json_encode(['state' => 3]);
			} else {
				echo json_encode(['state' => 7]);
			}
		} else if ($userType == 2) {
			$data['shop_email'] = $_POST['email'];
			$data['shop_password'] = md5($_POST['password']);
			$data['shop_name'] = $_POST['username'];

			$result = ShoperModel::create($data);
			if ($result) {
				echo json_encode(['state' => 4]);
			} else {
				echo json_encode(['state' => 7]);
			}
		}
	}


	//电话号码数据库验证--------------------------------------------------------
	public function phoneCheck(Request $request)
	{
		$num = $request->post('phone');
		$userResult = UserModel::get(['phone' => $num]);
		$shopResult = ShoperModel::get(['shop_phone' => $num]);
		$adminResult = AdminModel::get(['admin_phone' => $num]);
		if ($userResult || $shopResult || $adminResult) {
			echo json_encode(['state' => 3]);
		} else {
			echo json_encode(['state' => 4]);
		}
	}

	//获取手机验证码
	public function phoneCode()
	{
		if (Cookie::has('phoneTime')) {
		} else {
			Cookie::delete('phoneNum');

		}

		if (Cookie::get('phoneNum')) {
			if ((Cookie::get('phoneNum')) == $_POST['phone']) {
				echo json_encode(['state' => 1]);
			} else {
				$number = $_POST['phone'];
				Cookie::set('phoneNum', $number, 600);
				$code = mt_rand(100000, 999999);
				Vendor('phpApiDemo.Smsapi');
				$sms = new \Smsapi();
				$minute = 5;
				$sms->send($number, $code, $minute);
				Cookie::set('phoneTime', 1, 60);
				echo json_encode(['state' => 2, 'num' => $code]);
			}
		} else {
			$number = $_POST['phone'];
			Cookie::set('phoneNum', $number, 600);
			$code = mt_rand(100000, 999999);
			Vendor('phpApiDemo.Smsapi');
			$sms = new \Smsapi();
			$minute = 5;
			$sms->send($number, $code, $minute);
			Cookie::set('phoneTime', 1, 60);
			echo json_encode(['state' => 2, 'num' => $code]);
		}
	}

	//电话号码注册信息插入
	public function teldataInsert(Request $request)
	{
		$usetype = $request->post('useType');
		$phone = $request->post('phone');
		$pwd = md5($request->post('pwd'));
		$_SERVER['REMOTE_ADDR'] == '::1' ? $ip = '127.0.0.1' : $ip = $_SERVER['REMOTE_ADDR'];
		$ip = ip2long($ip);
		$data['create_ip'] = $ip;
		$data['create_time'] = date('Y-m-d H:i:s');
		if ($usetype == 1) {
			$data['password'] = $pwd;
			$data['phone'] = $phone;
			$data['username'] = 1;
			$data['email'] = 1;
			$data['grade'] = 10;

			$result = UserModel::create($data);
			if ($result) {
				echo json_encode(['state' => 7]);
			} else {
				echo json_encode(['state' => 8]);
			}
		} else if ($usetype == 2) {
			$data['shop_name'] = $request->post('shopname');
			$data['shop_email'] = 1;
			$data['shop_phone'] = $phone;
			$data['shop_password'] = $pwd;

			$result = ShoperModel::create($data);
			if ($result) {
				echo json_encode(['state' => 9]);
			} else {
				echo json_encode(['state' => 8]);
			}
		}
	}

	//用户登录---------------------------------------------------------------
	public function login()
	{
		if (Cookie::get('autoname') != 'false') {
			$data['username'] = Cookie::get('autoname');
			$data['password'] = Cookie::get('autopassword');
			$this->assign('autodata', $data);
		}

        //新浪第三方登录
        $o = new SaeTOAuthV2(WB_AKEY,WB_SKEY);

        //获取跳转到微博的url
        $code_url = $o->getAuthorizeURL(WB_CALLBACK_URL);

        //传递参数,渲染页面
        $this->assign('url',$code_url);

		return $this->fetch();
	}

	public function nameCheck(Request $request)
	{
		$username = $request->post('username');
		$userResult = UserModel::get(['username' => $username]);
		$shoperResult = ShoperModel::get(['shoper_name' => $username]);
		$shopReuslt = ShoperModel::get(['shop_name' => $username]);
		$adminResult = AdminModel::get(['admin_name' => $username]);

		if ($userResult || $shoperResult || $shopReuslt || $adminResult) {
			echo json_encode(['state' => 5]);
		} else {
			echo json_encode(['state' => 6]);
		}
	}

	//查询用户名 密码是否匹配, 如果选择记住密码就设置cookie
	public function loginCheck(Request $request)
	{
		$useType = $request->post('useType');
		$username = $request->post('name');
		$rem = $request->post('rem');
		$pwd = md5($request->post('pwd'));
		if ($useType == 1) {
			$userResult = UserModel::where('phone', '=', $username)->where('password', '=', $pwd)->select();
			$shopResult = ShoperModel::where('shop_phone', '=', $username)->where('shop_password', '=', $pwd)->select();
			$adminResult = AdminModel::where('admin_phone', '=', $username)->where('admin_password', '=', $pwd)->select();


			//test
//			var_dump($userResult, $shopResult, $adminResult);
			if ($userResult || $shopResult || $adminResult) {

				//判断通过什么进行登录的, 方便修改个人信息 0普通用户 1店名, 2管理员
				//保存用户id方便修改信息
				if ($userResult) {
					Cookie::set('loginType', 0);
					foreach ($userResult as $val) {
						Cookie::set('uid', $val->uid);
					}
				} else if ($shopResult) {
					foreach ($shopResult as $val) {
						Cookie::set('uid', $val->shop_id);
					}
					Cookie::set('loginType', 1);
				} else if ($adminResult) {
					foreach ($adminResult as $val) {
						Cookie::set('uid', $val->admin_id);
					}
					Cookie::set('loginType', 2);
				}

				if ($rem == 'true') {
					Cookie::set('autoname', $username, 3600 * 24 * 30);
					Cookie::set('autopassword', $request->post('pwd'), 3600 * 24 * 30);
				} else {
					Cookie::set('autoname', 'false', 3600);
					Cookie::set('autopassword', 'false', 3600);
				}

				//通过哪种方式登录, 电话邮箱用户名
				Cookie::set('loginBy', 'tel');
				//用于判断是否登录(和修改个人信息
				Cookie::set('tel', $username);
				echo json_encode(['state' => 7]);
			} else {
				echo json_encode(['state' => 8]);
			}
		} else if ($useType == 2) {
			$userResult = UserModel::where('email', '=', $username)->where('password', '=', $pwd)->where('')->select();
			$shopResult = ShoperModel::where('shop_email', '=', $username)->where('shop_password', '=', $pwd)->select();
			$adminResult = AdminModel::where('admin_email', '=', $username)->where('admin_password', '=', $pwd)->select();


			if ($userResult || $shopResult || $adminResult) {
				if ($rem == 'true') {
					Cookie::set('autoname', $username, 3600 * 24 * 30);
					Cookie::set('autopassword', $request->post('pwd'), 3600 * 24 * 30);
				} else {
					Cookie::set('autoname', 'false', 3600);
					Cookie::set('autopassword', 'false', 3600);
				}
				//判断通过什么进行登录的, 方便修改个人信息 0普通用户 1店名, 2管理员
				if ($userResult) {
					Cookie::set('loginType', 0);
					foreach ($userResult as $val) {
						Cookie::set('uid', $val->uid);
					}
				} else if ($shopResult) {
					foreach ($shopResult as $val) {
						Cookie::set('uid', $val->shop_id);
					}
					Cookie::set('loginType', 1);
				} else if ($adminResult) {
					foreach ($adminResult as $val) {
						Cookie::set('uid', $val->admin_id);
					}
					Cookie::set('loginType', 2);
				}

				//通过什么登录电话邮箱,用户名
				Cookie::set('loginBy', 'email');
				Cookie::set('email', $username);
				echo json_encode(['state' => 7]);
			} else {
				echo json_encode(['state' => 8]);
			}
		} else if ($useType == 3) {
			$userResult = UserModel::where('username', '=', $username)->where('password', '=', $pwd)->select();
			$shopResult = ShoperModel::where('shop_name', '=', $username)->where('shop_password', '=', $pwd)->select();
			$adminResult = AdminModel::where('admin_name', '=', $username)->where('admin_password', '=', $pwd)->select();
			if ($userResult || $shopResult || $adminResult) {
				if ($rem == 'true') {
					echo 1;
					Cookie::set('autoname', $username, 3600 * 24 * 30);
					Cookie::set('autopassword', $request->post('pwd'), 3600 * 24 * 30);
				} else {
					Cookie::set('autoname', 'false', 3600);
					Cookie::set('autopassword', 'false', 3600);
				}
				//判断通过什么进行登录的, 方便修改个人信息 0普通用户 1店表, 2管理员表
				if ($userResult) {
					Cookie::set('loginType', 0);
					foreach ($userResult as $val) {
						Cookie::set('uid', $val->uid);
					}
				} else if ($shopResult) {
					foreach ($shopResult as $val) {
						Cookie::set('uid', $val->shop_id);
					}
					Cookie::set('loginType', 1);
				} else if ($adminResult) {
					foreach ($adminResult as $val) {
						Cookie::set('uid', $val->admin_id);
					}
					Cookie::set('loginType', 2);
				}
				//通过什么用户名登录, 电话邮箱用户名
				Cookie::set('loginBy', 'username');
				Cookie::set('username', $username);
				echo json_encode(['state' => 7]);
			} else {
				echo json_encode(['state' => 8]);
			}
		}
	}


	//------------------微博第三方登录------
    public function foot()
    {

        // return $this->fetch();
        // return 'a';
        // $path = STATIC_HOME;
        //$this->assign(['path' => $path]);
        // $this->display();
        //return $this->fetch();
        // dump(1);
    }

    //--------微博第三方登录接口SDK测试

    //获取跳转到微博的url,
    public function sina()
    {
        //实例化auth类
        $o = new SaeTOAuthV2(WB_AKEY,WB_SKEY);

        //获取跳转到微博的url
        $code_url = $o->getAuthorizeURL(WB_CALLBACK_URL);

        //传递参数,渲染页面
        $this->assign('url',$code_url);
        //dump(APP_PATH);
        return $this->fetch();

    }

    //获取跳转到微博的回调url,
    public function callback()
    {
        //实例化auth类
        $o = new SaeTOAuthV2(WB_AKEY,WB_SKEY);
        $keys = array();

        //接收传值
        $param = Request::instance()->param();
        //dump($param);

        //获取url,token和code的三者的值
        $keys['code'] = $param['code'];
        $keys['redirect_uri'] = WB_CALLBACK_URL;
        $token = $o->getAccessToken('code',$keys);

        //若口令token存在,存入session , 否则返回提示信息
        if ($token) {

	//存在		
	 //授权成功 , 将token保存到session中
            	Session::set('token',$token);

         	$webSite = WEB_SITE;
            	$this->assign('webSite',$webSite);
            	return $this->fetch('callback');
        } else {
            //授权失败
            return $this->errors('授权失败');
        }
    }

    //微博信息显示页面
    public function weibolist()
    {
        //实例化类
        $o = new SaeTClientV2(WB_AKEY,WB_SKEY,Session::get('token')['access_token']);

        //或 ms信息, uid , 用户信息
        $ms = $o->home_timeline();
        $uid_get = $o->get_uid();
        $uid = $uid_get['uid'];
        $user_message = $o->show_user_by_id($uid);

	//查看,是否插入数据库
	$user = UserModel::get(['username'=>"$uid"]);
	if (!$user){

		//不存在, 插入数据库
		$dbData = [
			'username' =>"$uid",
			'password' => 1 ,
			'email'       => 1 ,
			'phone'	  => 1 ,
			'after_login' =>0 ,
			'allow_login' => 1 ,
			'is_active'     => 1 , 
			'user_del'	    => 0 ,
			'level_id'      => 1 ,
			'grade'        => 20 ,
		];
		$res2 = UserModel::create($dbData);
		
		if ($res2) {
			
			$username = $res2->username;
			$userId = $res2->uid;
			//echo '22222222成功';		
		} else {
			//echo '4444444444444失败';
		}

	} else {
	
		$username = $user->username;
		$userId = $user->uid;
	}
	//设置登录判断条件
	cookie('loginBy','username');
	cookie('username',"$username");
	cookie('loginType', 0 );
	cookie('uid' , $userId);


        //传递参数,渲染页面
        $webSite = WEB_SITE;
        $this->assign('webSite',$webSite);
        $this->assign('ms',$ms);
        $this->assign('uid' , $uid);
        $this->assign('user_message' , $user_message);
        return $this->fetch();

    }

    //发微博
    public function send()
    {
        //实例化类
        $o = new SaeTClientV2(WB_AKEY,WB_SKEY,Session::get('token')['access_token']);
        //获取text的值
        $res = $o->update(Request::instance()->param()['text']);

        //通过判断错误号,判断微博是否发送成功
        if (isset($res['error_code']) && $res['error_code'] > 0) {

            return $this->error('发送失败');
        } else {

            //发送成功,获取用户相关细信息
            $ms = $o->home_timeline();
            $uid_get = $o->get_uid();
            $uid = $uid_get['uid'];
            $user_message = $o->show_user_by_id($uid);

            //传递参数,渲染页面
            $this->assign('ms',$ms);
            $this->assign('uid' , $uid);
            return $this->fetch('weibolist');	//注意

        }

    }





}
